<template>
    <div>
        <!-- 卡片视图区域 -->
        <el-card>
            <el-form :model="changeForm" :rules="ruleForm" ref="changeFormRef">
                <el-row :gutter="20">
                <el-col :span="8"> 
                    <el-form-item prop="username">
                        <el-input placeholder="请输入用户名" v-model="changeForm.username"> </el-input>
                    </el-form-item>
                        
                    
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="updateuser">修改</el-button>
                </el-col>
            </el-row>
            </el-form>

            <!-- 头像上传 -->
            <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-card>
    </div>
</template>

<script>
export default {
    data() {
        return {
            //图片的url
            imageUrl: '',
            //双向绑定修改用户名
            changeForm: {
                username: '',
            },
            //验证规则
            ruleForm: {
                username: [
                    { required: true, message: '请输入您需要修改的用户名', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        //修改用户名
        async updateuser() {
            const { data: res } = await this.$http.put();
        },

        //图片上传逻辑
        handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt10M = file.size / 1024 / 1024 < 10;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt10M) {
          this.$message.error('上传头像图片大小不能超过 10MB!');
        }
        return isJPG && isLt10M;
      }
    }
}
</script>

<style lang="less" scoped>
    .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>